<script setup>
import {ref} from 'vue'
import axios from 'axios'
import {ElMessage,ElMessageBox} from 'element-plus'

import { format } from 'date-fns';
import qs from "qs";
// 转换毫秒数为日期格式
function formatTimestamp(timestamp) {
  return format(new Date(timestamp), 'yyyy-MM-dd HH:mm:ss');
}
// 将毫秒数转换为yyyy-m-d hh:mm:ss格式，与上相同，只需要改这一句
// const dt = new Date(originVal)
const input = ref('')
fetchData(1); // 初始加载第一页数据


//分页
// const tableData = ref([]); // 当前页的数据列表
const total = ref(0); // 总记录数
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的记录数

function fetchData(page) {
    // 发送请求到后端获取数据
    axios({
        method:"post",
        url: 'http://localhost:8080/admin/getOrderList',
        data: {"currentpage":page},
        transformRequest: [ function(data){
            return qs.stringify(data)  //使用Qs将请求参数序列化
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
        }
    }).then(response => {
        tableData.value = [];
        total.value = response.data.total;
        // currentPage.value = response.data.pageNum;
        response.data.list.forEach(item => {
            tableData.value.push(item);
        });
        // tableData.value = response.data.list;

    })
        .catch(error => {
            console.error("Error fetching data:", error);
        });
};

function handlePageChange(newPage){
    currentPage.value = newPage;
    fetchData(newPage);
};


//表格数据
const tableData =ref([])
function getAll(){
  axios({
    method:"get",
    url:"http://localhost:8080/admin/getOrderList"
  }).then((response)=>{
    tableData.value=response.data
  }).catch((error)=>{
    console.log(error);
  })
}
fetchData(1); // 初始加载第一页数据


function agreeOrder(oid) {
  ElMessageBox.confirm('确定要同意这个退款请求吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios({
      method: 'post',
      url: `http://localhost:8080/admin/IfrtMoney`,
      params: {
        oid: oid,
        rtmoney: '1' // '1'代表退款成功，即审核通过
      }
    }).then((response) => {
      fetchData(1); // 初始加载第一页数据
      if (response.data === 1) {
        ElMessage({
          type: 'success',
          message: '同意成功'
        });
      } else {
        ElMessage({
          type: 'error',
          message: '同意失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '同意请求失败'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    });
  });
}

// 拒绝订单退款
function rejectOrder(oid) {
  ElMessageBox.confirm('确定要拒绝这个退款请求吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios({
      method: 'post',
      url: `http://localhost:8080/admin/IfrtMoney`,
      params: {
        oid: oid,
        rtmoney: '0' // '0'代表退款失败，即审核失败
      }
    }).then((response) => {
      if (response.data === 0) {
        fetchData(1); // 初始加载第一页数据
        ElMessage({
          type: 'success',
          message: '拒绝成功'
        });
      } else {
        ElMessage({
          type: 'error',
          message: '拒绝失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '拒绝请求失败'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    });
  });
}

</script>

<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="max-width: 100%">
      <el-row>
        <el-col :span="4">
          <el-input
              v-model="input"
              style="width: 200px"
              placeholder="请输入你要查询的订单信息"
              clearable
          />
        </el-col>
        <el-col :span="20">

          <el-button type="primary" class="searchbtn" >
            <el-icon class="icon-search"><Search /></el-icon>查询
          </el-button>
        </el-col>
      </el-row>


      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="oid" label="订单编号" width="100" align="center" />
        <el-table-column prop="gname" label="商品名称" width="100" align="center" />
        <el-table-column prop="sloginname" label="卖家账号" width="100" align="center" />
        <el-table-column prop="bloginname" label="买家账号" width="100" align="center" />
        <el-table-column prop="gimage" label="商品图片" width="150" align="center">
          <template #default="scope">
            <el-image style="width: 100px; height: 100px;" :src="scope.row.gimage"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量" width="50" align="center" />
        <el-table-column prop="price" label="商品价格" width="50" align="center" />
        <el-table-column prop="payment" label="交易方式" width="50" align="center" />
        <el-table-column prop="send" label="邮寄方式" width="50" align="center" />
        <el-table-column prop="address" label="收货地址" width="150" align="center" />
        <el-table-column prop="dltime" label="发货时间" width="150" align="center">
          <template #default="scope">
            <span v-if="scope.row.dltime">{{ formatTimestamp(scope.row.dltime) }}</span>
            <span v-else>未发货</span>
          </template>
        </el-table-column>
        <el-table-column prop="rvtime" label="收货时间" width="150" align="center">
          <template #default="scope">
            <span v-if="scope.row.rvtime">
              {{ formatTimestamp(scope.row.rvtime)}}
            </span>
            <span v-else>
              未收货
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="rtmoney" label="订单退款" width="100" align="center" >
          <template #default="scope">
            <!-- 使用三元运算符来判断审核状态，并设置不同的类型 -->
            <el-tag :type="scope.row.rtmoney === '退款成功' ? 'success' : (scope.row.rtmoney === '退款失败' ? 'danger' : 'warning')">
              {{ scope.row.rtmoney }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="退款理由" width="150" align="center" />
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="scope">
            <!-- 同意按钮，仅当状态为 '退款审核中' 时显示 -->
            <el-tooltip effect="dark" content="同意" v-if="scope.row.rtmoney === '退款审核中'">
              <el-button style="margin-bottom: 5px" type="success" @click="agreeOrder(scope.row.oid)">
                <el-icon>同意</el-icon>
              </el-button>
            </el-tooltip>
            <br>
            <!-- 拒绝按钮，仅当状态为 '退款审核中' 时显示 -->
            <el-tooltip effect="dark" content="拒绝" v-if="scope.row.rtmoney === '退款审核中'">
              <el-button type="error" @click="rejectOrder(scope.row.oid)">
                <el-icon>拒绝</el-icon>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
        <el-pagination
                size="small"
                background
                layout="prev, pager, next"
                :total="total"
                v-model:currentPage="currentPage"
                @current-change="handlePageChange"
                class="mt-4"
        />
    </el-card>
  </div>
</template>


<style scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.searchbtn{
  float: right;
}

.icon-search{
  margin-right: 10px;
}
.el-table{
  margin-top: 20px;
}
</style>
